<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title="isAdd ? '新增轮播图' : '编辑轮播图'" left @close="closeDialog" >
    <div style="padding: 0 20px">
      <p style="margin-top:-20px;">首页顶部建议尺寸：图片宽度750。</p>
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
        <el-form-item label="轮播图名称:" prop="carouse_name">
          <el-input v-model="form.carouse_name" style="width: 300px;" />
        </el-form-item>
        <p><strong>上传图片并配置图片跳转地址：</strong></p>
        <p>至少上传一张，最多上传10张；支持gif、jpeg、png三种格式；大小不超过3M;</p>
        <div
          v-for="(item,index) in form.carouseList"
          :key="index"
          style="display:flex;align-items:center;margin: 10px 0">
          <div class="slide-item">
            <i class="el-icon-sort-down" style="font-size: 25px;" @click="bottomClick(item)"/>
            <i class="el-icon-sort-up" style="font-size: 25px;margin-left:-10px" @click="topClick(item)"/>
          </div>
          <el-upload
            :show-file-list="false"
            :on-success="userImgSuccess"
            :before-upload="beforeUserImgUpload"
            :action="userHeadUploadApi"
            class="avatar-uploader">
            <img v-if="item.url" :src="item.url" class="avatar" @click="list=item" >
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="list=item" />
          </el-upload>
          <div>
            <el-button style="width:300px;margin-left:10px" size="small" @click="selectLink(item)"><div class="link_style">{{ item.link_name?item.link_name:'选择链接地址' }}</div></el-button>
            <i class="el-icon-circle-close" style="font-size:18px;margin-top:6px;cursor:pointer" @click="deleteSlide(index)" />
          </div>
        </div>
        <el-button
          v-if="btnShow"
          type="primary"
          size="small"
          style="width:300px;margin-left:105px"
          @click="addSlide">添加轮播图</el-button>
      </el-form>
    </div>
    <!-- 选择图片组件 -->
    <el-dialog
      :visible.sync="innerVisible"
      :before-close="handleClose"
      width="1100px"
      top="2vh"
      append-to-body
      style="padding:0">
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose()">取 消</el-button>
        <el-button type="primary" size="small" @click="confirmImage()">确 定</el-button>
      </div>
    </el-dialog>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button type="primary" size="small" @click="doSubmit">确认</el-button>
    </div>
    <formDetail ref="formDetail" :parent-data="parentData" :row-data="rowData" @fun="fun"/>
    <!--链接地址弹出框-->
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import Cookies from 'js-cookie'
import { saveSlideshow } from '@/api/design/slideshowForm'
import formDetail from './formDetail'

export default {
  components: { formDetail },
  data() {
    return {
      // 调用组件formDetail给出默认值
      rowData: {},
      parentData: {},
      innerVisible: false,
      // 附带参数， 公司id
      company_id: Cookies.get('company_id'),
      dialog: false,
      list: '',
      // 定义当前当前选择的图片行索引
      rowIndex: '',
      isAdd: false,
      form: {
        carouse_id: '',
        carouse_name: '',
        url: '',
        carouseList: []
      },
      rules: {
        carouse_name: [
          { required: true, message: '请填写轮播图名称', trigger: 'blur' }
        ]
      },
      // 是否显示"添加轮播图"按钮
      btnShow: true,
      imageUrl: '' // 子组件传递过来的图片url
    }
  },
  computed: {
    ...mapGetters([
      'userHeadUploadApi'
    ])
  },
  methods: {
    // 确定选择图片
    confirmImage() {
      this.list.url = this.imageUrl
      this.innerVisible = false
      // 父组件点击事件
      this.$refs.son.toggleSelection()
    },
    // 取消选择图片
    handleClose() {
      this.innerVisible = false
      // 父组件点击事件
      this.$refs.son.toggleSelection()
    },
    resetForm() {
      this.dialog = false
      this.btnShow = true
    },
    userImgSuccess(res, file) {
      // 后台返回的oss地址，回显图片内容,存储对象里，用于保存信息时使用
      this.list.url = res
    },
    beforeUserImgUpload(file) {
      let isJPG = false
      if (file.type === 'image/jpeg' || file.type === 'image/gif' || file.type === 'image/png') {
        isJPG = true
      }
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isJPG) {
        this.$message.error('上传图片只能是gif、jpeg、png格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传图片大小不能超过3MB!')
      }
      return isJPG && isLt3M
    },
    /* 增加轮播图事件*/
    addSlide() {
      const link = { url: '', type: 0, link_url: '', link_name: '' }
      this.form.carouseList.push(link)
      if (this.form.carouseList.length === 10) {
        this.btnShow = false
      }
    },
    /* 删除轮播图事件*/
    deleteSlide(index) {
      this.form.carouseList.splice(index, 1)
    },
    cancel() {
      this.resetForm()
    },
    closeDialog() {
      this.$refs['form'].resetFields()
      this.resetForm()
    },
    // 链接地址弹出框
    selectLink(item) {
      this.$refs.formDetail.dialog = true
      this.$refs.formDetail.selectType = 3
      this.rowIndex = this.form.carouseList.indexOf(item)
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const carouseArray = this.form.carouseList
          let num = 0
          // 判断轮播图中的图片和链接地址是否都是空的,若都是空值，则不需要保存空的数组记录
          const array = []
          if (carouseArray) {
            carouseArray.forEach((item, index) => {
              if (item.url || item.link_url) {
                array.push(carouseArray[index])
                if (item.url) {
                  num = num + 1
                }
              }
            })
          }
          // 判断是否没有上传图片
          if (num === 0) {
            this.$message({
              message: '请至少上传一张图片！',
              type: 'warning',
              duration: 1500
            })
            return false
          }
          this.form.carouseList = array
          saveSlideshow(this.form).then(res => {
            if (res) {
              // 执行成功
              this.resetForm()
              this.$notify({
                title: '修改成功',
                type: 'success',
                duration: 2500
              })
              this.$parent.init()
            } else {
              this.$notify({
                title: res,
                type: 'error',
                duration: 2500
              })
            }
          }).catch(err => {
            console.log(err.response.data.message)
          })
        }
      })
    },
    bottomClick(item) {
      const index = this.form.carouseList.indexOf(item)
      if (index !== this.form.carouseList.length - 1) {
        this.form.carouseList[index] = this.form.carouseList.splice(index + 1, 1, this.form.carouseList[index])[0]
      } else {
        this.$message({
          message: '已经是最底端了，不能再移动了。。。',
          type: 'warning'
        })
      }
    },
    topClick(item) {
      const index = this.form.carouseList.indexOf(item)
      if (index !== 0) {
        this.form.carouseList[index] = this.form.carouseList.splice(index - 1, 1, this.form.carouseList[index])[0]
      } else {
        this.$message({
          message: '已经是最顶端了，不能再移动了。。。',
          type: 'warning'
        })
      }
    },
    // 接受子组件传递的值
    fun(data) {
      // 设置选择的跳转地址
      this.form.carouseList[this.rowIndex].link_url = data.p_id
      this.form.carouseList[this.rowIndex].link_name = data.p_name
      this.form.carouseList[this.rowIndex].type = data.type
      this.$forceUpdate()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
  .avatar-uploader .el-upload {
  width: 50px;
  height: 50px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.element .style {
  margin: 0px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  cursor: pointer;
}
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 16px;
  cursor: pointer;
}
.el-form-item__contentn {
  margin-left: 50px;
}
.link_style{
  width: 280px;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.slide-delete{
  width: 10px;
  height: 20px;
  position: absolute;
  left: 310px;
  top:0px;
  padding-top:5px;
}
</style>
